package com.qf.sys.service.impl;

import com.qf.entity.sys.SysUser;
import com.qf.exception.CustomerException;
import com.qf.sys.dao.SysUserDao;
import com.qf.sys.param.LoginParam;
import com.qf.sys.service.SysUserService;
import com.qf.utils.RedisUtil;
import com.qf.utils.SendMailUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author zdl
 * @date 2025/2/26
 */
@Service
public class SysUserServiceImpl implements SysUserService {

    @Resource
    private SysUserDao sysUserDao;
    @Resource
    private RedisUtil redisUtil;
    @Override
    public String  loginByUserNameAndPassword(LoginParam loginParam) {
        SysUser sysUser = sysUserDao.selectSysUserByUserName(loginParam.getUsername());
        if (sysUser == null){
            throw  new CustomerException("5001","账号不存在!");
        }
        if (!(loginParam.getPassword().equals(sysUser.getPassword()))){
            throw new CustomerException("5002","密码错误!");
        }
        if (!(sysUser.getStatus().equals("0"))){
            throw new CustomerException("5003","账号状态异常!");
        }
        if (sysUser.getDelFlag() != 0){
            throw new CustomerException("5004","账号已删除!");
        }
        String token = UUID.randomUUID().toString();
        // 缓存token
        redisUtil.setCacheObject(token,sysUser,60*3, TimeUnit.SECONDS);
        return token;
    }

    @Override
    public String sendMailCode(String email) {
        // 发送邮件验证码
        String verificationCode  = SendMailUtil.sendVerificationCode(email);
        redisUtil.setCacheObject(email, verificationCode , 60 * 3, TimeUnit.SECONDS);
        if (redisUtil.getCacheObject(email) == null){
            throw new CustomerException("5005","验证码已经失效!");
        }
        return verificationCode ;
    }
}
